package com.ruoyi.web.controller.system;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.pig4cloud.captcha.SpecCaptcha;
import com.pig4cloud.captcha.base.Captcha;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.LmSysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.web.service.ConfigService;
import com.ruoyi.system.mapper.LmSysUserMapper;
import com.ruoyi.system.service.ILmSysUserService;
import com.ruoyi.web.controller.utils.CacheUtil;
import com.ruoyi.web.controller.utils.IpUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2023-12-05
 */
@Controller
@RequestMapping("/admin/user")
public class LmSysUserController extends BaseController {

    @Autowired
    private ILmSysUserService lmSysUserService;

    @Autowired
    private ConfigService configService;

    /**
     * 验证码
     *
     * @return {@link AjaxResult}
     * @throws Exception 例外
     */
    @ApiOperation(value = "获得验证码")
    @GetMapping("/captcha")
    @ResponseBody
    public AjaxResult captcha() {
        // 生成图片验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(90, 36, 4);
        // 设置字体（如果有默认字体，可以不用设置）
        specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 30));
        // 设置类型为纯数字
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        String text = specCaptcha.text().toLowerCase();
        // 设置背景颜色
        UUID uuid = UUID.randomUUID();
        // 保存验证码到本地缓存
        CacheUtil.put(uuid.toString(), text);
        JSONObject data = new JSONObject();
        String base64 = specCaptcha.toBase64();
        data.put("key", uuid);
        data.put("code", base64);
        return AjaxResult.success(data);
    }

    /**
     * 登录
     *
     * @param request 请求
     * @return {@link AjaxResult }
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(String username, String password, String key, String code, HttpServletRequest request) {

//        Object localCode = CacheUtil.get(key);
//        if (localCode == null) {
//            return AjaxResult.error("验证码已失效或已过期");
//        }
//        if (!localCode.equals(code)) {
//            return AjaxResult.error("验证码错误");
//        }
        LmSysUser lmSysUser = this.lmSysUserService.getLmSysUserByUsername(username);
        if (lmSysUser == null) {
            return AjaxResult.error("用户名或密码错误");
        }
        String salt = lmSysUser.getSalt();
        String md5Password = md5Hex(password + salt);

        LmSysUser user = lmSysUserService.login(username, md5Password);
        if (user == null) {
            return AjaxResult.error("用户名或密码错误");
        }
        int status = user.getStatus();
        if (status == 2) {
            return AjaxResult.error("该账户已被禁用");
        }
        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();

        String ip = IpUtil.getIpAddress(request);
        user.setToken(token);
        user.setLastLoginIp(ip);
        user.setLastLoginTime(LocalDateTime.now());
        lmSysUserService.updateById(user);
        user.setPassword(null);
        return AjaxResult.success(user);
    }

    /**
     * 注销
     *
     * @return {@link AjaxResult}
     */
    @ApiOperation(value = "注销")
    @GetMapping("/logOut")
    @ResponseBody
    public AjaxResult logOut() {
        String tokenValue = StpUtil.getTokenValue();
        StpUtil.kickout(tokenValue);
        return AjaxResult.success(null);
    }

    /**
     * 获取管理员列表
     *
     * @param page    第页
     * @param limit   限制
     * @param username 关键字
     * @return {@link AjaxResult}
     */
    @ApiOperation(value = "获取管理员列表")
    @GetMapping("/getAdminList")
    @ResponseBody
    public TableDataInfo getAdminList(Integer page, Integer limit, String username, Integer status) {
        List<LmSysUser> adminUserList = lmSysUserService.getAdminList(page, limit, username,status);

        return getDataTable(adminUserList);
    }


    @Autowired
    private LmSysUserMapper userMapper;

    /**
     * 获取管理员列表
     *
     * @param page    第页
     * @param limit   限制
     * @param username 关键字
     * @return {@link AjaxResult}
     */
    @ApiOperation(value = "获取管理员列表")
    @GetMapping("/getAdminNoPageList")
    @ResponseBody
    public AjaxResult getAdminNoPageList() {
        LmSysUser user = new LmSysUser();
        List<LmSysUser> userList = userMapper.selectUserList(user);

        return AjaxResult.success(userList);
    }

    /**
     * 按id获取管理员
     *
     * @param id id
     * @return {@link AjaxResult}
     */
    @ApiOperation(value = "按id获取管理员")
    @GetMapping("/getAdminById")
    @ResponseBody
    public AjaxResult getAdminById(Integer id) {
        LmSysUser sysUser = lmSysUserService.getById(StpUtil.getLoginIdAsLong());
        if (sysUser == null) {
            return AjaxResult.error("用户不存在");
        }
        LmSysUser SysUser = lmSysUserService.getById(id);
        return AjaxResult.success(SysUser);
    }

    /**
     * 后台更新密码
     *
     * @param password 密码
     * @return {@link AjaxResult}
     */
    @ApiOperation(value = "后台更新密码")
    @PostMapping("/updatePassWord")
    @ResponseBody
    public AjaxResult updatePassWord(@RequestParam("oldPassword")String oldPassword,@RequestParam("newPassword") String newPassword) {
        LmSysUser sysUser = lmSysUserService.getById(StpUtil.getLoginIdAsLong());
        if (sysUser == null) {
            return AjaxResult.error("用户不存在");
        }
        //校验旧密码
        String oldPasswordStr = md5Hex(oldPassword + sysUser.getSalt());
        if (!sysUser.getPassword().equals(oldPasswordStr)){
            return AjaxResult.error("旧密码错误！");
        }

        String newPasswordStr =  md5Hex(newPassword + sysUser.getSalt());
        if (sysUser.getPassword().equals(newPasswordStr)){
            return AjaxResult.error("新密码和旧密码不能相同！");
        }


        String salt = RandomUtil.randomString(8);
        String newWord = md5Hex(newPassword + salt);
        sysUser.setPassword(newWord);
        sysUser.setSalt(salt);
        lmSysUserService.updateById(sysUser);
        return AjaxResult.success("修改成功");
    }

    /**
     * 添加和更新管理员
     *
     * @param sysUser sys用户
     * @return {@link AjaxResult}
     */
    @ApiOperation(value = "添加和更新管理员")
    @PostMapping("/addAndUpdateAdmin")
    @ResponseBody
    public AjaxResult addAndUpdateAdmin( LmSysUser sysUser) {
        LmSysUser sysUserById = lmSysUserService.getById(StpUtil.getLoginIdAsLong());
        if (sysUserById == null) {
            return AjaxResult.error("用户不存在");
        }
        String salt = RandomUtil.randomString(8);
        if (sysUser.getId() == null) {
            String password = sysUser.getPassword();
            String newPassWord = DigestUtil.md5Hex(password + salt);
            sysUser.setPassword(newPassWord);
            sysUser.setCreateTime(LocalDateTime.now());
            sysUser.setSalt(salt);
            sysUser.setIdentity(2);
            lmSysUserService.save(sysUser);
        } else {
            LmSysUser user = lmSysUserService.getById(sysUser.getId());
            if (user != null) {
                sysUser.setId(user.getId());
            } else {
                return AjaxResult.success("用户不存在");
            }
            if (sysUser.getPassword() != null) {
                String password = sysUser.getPassword();
                String newPassWord = DigestUtil.md5Hex(password + salt);
                sysUser.setPassword(newPassWord);
                sysUser.setSalt(salt);
            }
            sysUser.setUpdateTime(LocalDateTime.now());
            lmSysUserService.updateById(sysUser);
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 更新管理员状态
     *
     * @param id     id
     * @param status 状态
     * @return {@link AjaxResult}
     */
    @ApiOperation(value = "更新管理员状态")
    @GetMapping("/updateAdminStatus")
    @ResponseBody
    public AjaxResult updateAdminStatus(@RequestParam("id") Integer id, @RequestParam("status") Integer status) {
        LmSysUser sysUser = lmSysUserService.getById(StpUtil.getLoginIdAsLong());
        if (sysUser == null) {
            return AjaxResult.error("用户不存在");
        }
        LmSysUser SysUser = new LmSysUser();
        SysUser.setId(id);
        SysUser.setStatus(status);
        lmSysUserService.updateById(SysUser);
        return AjaxResult.success("操作成功");
    }


    /**
     * 删除admin
     * del admin
     *
     * @param id id
     * @return {@link AjaxResult}
     */
    @ApiOperation(value = "删除admin")
    @GetMapping("/delAdmin")
    @ResponseBody
    public AjaxResult deleteAdmin(Integer id) {
        LmSysUser sysUser = lmSysUserService.getById(StpUtil.getLoginIdAsLong());
        if (sysUser == null) {
            return AjaxResult.error("用户不存在");
        }
        lmSysUserService.removeById(id);
        return AjaxResult.success("删除成功");
    }
}

